package com.bskyb.rss.parser;

import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;

import android.util.Log;
import android.widget.Toast;

import com.bskyb.rss.FeedItem;
import com.bskyb.rss.R;
import com.bskyb.rss.RssFeed;

public class RssFeedHandler extends DefaultHandler {

	// Used to define what elements we are currently in
	private boolean inTitle = false;
	private boolean inLink = false;
	private boolean inDescription = false;
	private boolean inItem = false;

	private RssFeed rssFeed = new RssFeed();
	private FeedItem currentFeedItem;
	private String TAG = "RssFeedHandler";

	@Override
	public void startElement(String uri, String name, String qName,
			Attributes atts) {
		if (name.trim().equals("title")) {
			inTitle = true;
		} else if (name.trim().equals("description")) {
			inDescription = true;
		} else if (name.trim().equals("link")) {
			inLink = true;
		} else if (name.trim().equals("item")) {
			inItem = true;
			currentFeedItem = new FeedItem();
		}

	}

	@Override
	public void endElement(String uri, String name, String qName)
			throws SAXException {
		if (name.trim().equals("title")) {
			inTitle = false;
		} else if (name.trim().equals("description")) {
			inDescription = false;
		} else if (name.trim().equals("link")) {
			inLink = false;
		} else if (name.trim().equals("item")) {
			inItem = false;
			rssFeed.addFeedItem(currentFeedItem);
		}

	}

	@Override
	public void characters(char ch[], int start, int length) {
		String chars = (new String(ch).substring(start, start + length));
		if (inItem) {
			if (inTitle) {
				currentFeedItem.setTitle(chars);				
			} else if (inLink) {
				currentFeedItem.setLink(chars);				
			} else if (inDescription) {
				currentFeedItem.setDescription(chars);				
			}

		}
	}

	public RssFeed createFeed(URL url) throws ParserConfigurationException,
			SAXException, IOException {		
		SAXParserFactory spf = SAXParserFactory.newInstance();
		SAXParser sp = spf.newSAXParser();
		XMLReader xr = sp.getXMLReader();
		xr.setContentHandler(this);
		// TODO 
		// Banner for sky
		// proper images for news and sports
		//OPTIONAL.
		// Notification for changed feed..
		// Config screen being slow
		//

		URLConnection conn = url.openConnection();
		conn.setConnectTimeout(R.string.rssfeed_connecttimeout);
		conn.setReadTimeout(R.string.rssfeed_readtimeout);

		InputSource inputSource = new InputSource(conn.getInputStream());
		xr.parse(inputSource);
		return rssFeed;
	}

}
